package com.obradovicnjegovan.webprodavnica.services;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.crypto.hash.Sha1Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.obradovicnjegovan.webprodavnica.entities.Korisnik;
import com.obradovicnjegovan.webprodavnica.entities.TipKorisnika;

public class KorisnikRealm extends AuthorizingRealm {
	protected final Session session;

	public KorisnikRealm(Session session) {
		super(new MemoryConstrainedCacheManager());
		this.session = session;
		setName("localaccounts");
		setAuthenticationTokenClass(UsernamePasswordToken.class);
		setCredentialsMatcher(new HashedCredentialsMatcher(Sha1Hash.ALGORITHM_NAME));
	}
	
	@SuppressWarnings("unused")
	private Korisnik findByUsername(String username) {
		return (Korisnik) session.createCriteria(Korisnik.class).add(Restrictions.eq("username", username)).uniqueResult();
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		if (principals == null) throw new AuthorizationException("PrincipalCollection was null, which should not happen");

		if (principals.isEmpty()) return null;

		if (principals.fromRealm(getName()).size() <= 0) return null;

		String username = (String) principals.fromRealm(getName()).iterator().next();
		if (username == null) return null;
		Korisnik user = findByUsername(username);
		if (user == null) return null;
		
		Set<String> roles = new HashSet<String>(user.getRoles().size());
		for (TipKorisnika role : user.getRoles())
			roles.add(role.name());
		return new SimpleAuthorizationInfo(roles);
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = upToken.getUsername();
		if (username == null) { throw new AccountException("Null usernames are not allowed by this realm."); }
		Korisnik user = findByUsername(username);
		return new SimpleAuthenticationInfo(username, user.getEncodedPassword(), new SimpleByteSource(user.getPasswordSalt()), getName());
	}

}
